// pages/discovery/discovery.js
const { get, post, queryUserProfiles, queryUserAllInfo } = require('../../utils/api.js')
const { showError, showSuccess, showToast } = require('../../utils/util.js')
const { navigateTo } = require('../../utils/router.js')
const FreshTheme = require('../../utils/fresh-theme.js')

Page({
  data: {
    // 标签页状态
    activeTab: 0,  // 0: 认证用户, 1: 未认证用户
    
    // 推荐列表（未认证用户）
    recommendations: [],
    loading: false,
    loadingMore: false,
    
    // 全部认证用户列表
    verifiedUsers: [],
    verifiedUsersLoading: false,
    verifiedUsersTotal: 0,
    verifiedUsersPage: 1,
    verifiedUsersPageSize: 20,
    
    // 认证用户查找相关
    searchMode: 'list', // 'list' | 'simple' | 'advanced'
    searchResults: [],
    searchLoading: false,
    searchTotal: 0,
    searchPage: 1,
    
    // 当前用户索引
    currentIndex: 0,
    
    // 全部认证用户筛选条件
    verifiedFilters: {
      gender: '',
      ageRange: {
        minAge: 18,
        maxAge: 60
      },
      minHeight: 0,
      maxWeight: 0,
      educationRange: {
        minEducation: '',
        maxEducation: ''
      },
      minIncome: 0,
      occupation: '',
      parentsHasPension: null
    },
    
    // 显示认证用户筛选弹窗
    showVerifiedFilter: false,
    filters: {
      ageRange: [20, 35],
      heightRange: [160, 180],
      education: [],
      city: '',
      maxDistance: 50,
      onlyVerified: false,
      minCompatibility: 60
    },
    
    // 筛选选项
    educationOptions: [
      { label: '高中及以下', value: 'highschool' },
      { label: '大专', value: 'college' },
      { label: '本科', value: 'bachelor' },
      { label: '硕士', value: 'master' },
      { label: '博士', value: 'doctor' }
    ],
    
    // 普通查找筛选条件
    simpleFilters: {
      occupation: '',
      minHeight: 0,
      city: ''
    },
    
    // 高级筛选条件
    advancedFilters: {
      ageRange: [18, 35],
      heightRange: [150, 185],
      education: [],
      occupation: '',
      income: '0',
      interests: [],
      maxDistance: 50,
      onlyVerified: false
    },
    
    // 常见兴趣爱好
    commonInterests: [
      '运动健身', '音乐', '电影', '旅行', '美食', '读书',
      '摄影', '游戏', '绘画', '舞蹈', '瑜伽', '登山'
    ],

    // 认证用户筛选选项
    verifiedEducationOptions: [
      { text: '高中及以下', value: '高中' },
      { text: '中等职业教育', value: '中等职业教育' },
      { text: '专科', value: '专科' },
      { text: '本科', value: '本科' },
      { text: '硕士', value: '硕士' },
      { text: '博士', value: '博士' },
      { text: '博士后', value: '博士后' },
      { text: '其他', value: '其他' }
    ],
    
    // 认证用户教育选项（日系风格）
    verifiedEducationOptions: [
      '高中以下',
      '高中毕业', 
      '专科学历',
      '本科学历',
      '硕士研究生',
      '博士研究生'
    ],
    
    // 滑动相关
    swipeDirection: '',
    touchStartX: 0,
    touchStartY: 0,
    isDragging: false,
    cardTransform: '',
    
    // 用户详情
    showUserDetail: false,
    selectedUser: null,
    
    // 匹配成功
    showMatchSuccess: false,
    matchedUser: null,
    userAvatar: null,
    
    // 智能推荐设置
    smartMode: true,
    
    // 统计数据
    todayLikes: 0,
    todaySkips: 0,
    discoveryStats: {
      totalLikes: 0,
      totalMatches: 0,
      compatibilityAvg: 0
    },
    
    // Super Like 功能
    superLikesRemaining: 3,
    showSuperLikeSuccess: false,
    
    // 推荐质量反馈
    showFeedback: false,
    feedbackType: '',
    
    // 无更多用户提示
    showNoMoreUsers: false,
    
    // ========== 新增：清新自然风格 UI ==========
    // 清新筛选条件
    freshFilters: {
      gender: '',
      ageRange: { min: 18, max: 35 },
      heightRange: { min: 150, max: 185 },
      maxWeight: 0,
      education: '',
      minIncome: 0,
      occupation: '',
      location: '',
      parentsHasPension: null,
      activeBasicFilter: ''
    },
    
    // 清新风格教育选项
    freshEducationOptions: [
      '不限',
      '高中及以下',
      '大专',
      '本科',
      '硕士',
      '博士'
    ],
    
    // 显示高级筛选弹窗
    showAdvancedFilters: false,
    
    // 水平滑动相关
    swipeOffset: 0,
    swipeStartX: 0,
    swiping: false,
    
    // 当前筛选模式: 'basic' | 'advanced'
    filterMode: 'basic',
    
    // 圆形基础筛选器
    circularFilters: FreshTheme.circularFilters.basic,
    
    // 当前激活的筛选器
    activeBasicFilter: null,
    
    // 基础筛选器的值
    basicFilterValues: {
      age: { min: 18, max: 35, selected: false },
      gender: { value: '', selected: false },
      height: { min: 160, max: 180, selected: false },
      education: { value: '', selected: false },
      income: { min: 0, selected: false },
      occupation: { value: '', selected: false },
    },
    
    // 显示高级筛选
    showAdvancedFilter: false,
  },

  onLoad() {
    console.log('🚀 发现页面 onLoad 开始')
    
    // 初始化页面状态
    this.setData({
      activeTab: 0,
      searchMode: 'list',
      verifiedUsersLoading: false,
      loading: false,
      verifiedUsers: [],
      verifiedUsersTotal: 0,
      recommendations: []
    })
    
    console.log('✅ 页面初始化完成')
    
    // 加载认证用户数据
    this.loadVerifiedUsers()
    this.initPage()
  },

  onShow() {
    console.log('👁️ 发现页面 onShow')
    console.log('📊 当前状态:', {
      activeTab: this.data.activeTab,
      searchMode: this.data.searchMode,
      verifiedUsers: this.data.verifiedUsers ? this.data.verifiedUsers.length : 0,
      recommendations: this.data.recommendations ? this.data.recommendations.length : 0
    })
  },

  /**
   * 初始化页面
   */
  initPage() {
    // 获取用户头像配置
    const app = getApp()
    const userProfile = app.getUserProfile()
    if (userProfile && userProfile.avatarConfig) {
      this.setData({
        userAvatar: userProfile.avatarConfig
      })
    }
    
    // 初始化清新筛选条件
    this.setData({
      freshFilters: {
        gender: '',
        ageRange: { min: 18, max: 35 },
        heightRange: { min: 150, max: 185 },
        maxWeight: 0,
        education: '',
        minIncome: 0,
        occupation: '',
        location: '',
        parentsHasPension: null,
        activeBasicFilter: ''
      },
      // 精致筛选系统
      refinedActiveTab: 'basic',
      refinedFilters: {
        gender: '',
        occupation: '',
        minHeight: 0,
        location: '',
        hasHouse: null,
        experience: '',
        isPartyMember: null,
        locationAlt: '',
        hasProperty: null,
        personality: '',
        maritalStatus: '',
        wantsBaby: null,
        ageRange: { min: 18, max: 35 },
        heightRange: { min: 150, max: 185 },
        education: '',
        minIncome: 0
      }
    })
    
    // 默认加载认证用户
    this.loadVerifiedUsers()
  },

  /**
   * 加载推荐用户
   */
  loadRecommendations() {
    this.setData({ loading: true })
    
    // 获取用户匹配偏好
    const requestData = {
      ...this.data.filters,
      smartMode: this.data.smartMode,
      excludeIds: this.data.recommendations.map(user => user.userId),
      limit: 10
    }
    
    get('/api/discovery/recommendations', requestData)
      .then(data => {
        const newRecommendations = data.users || []
        
        // 计算兼容性评分
        const enhancedRecommendations = newRecommendations.map(user => {
          const compatibility = this.calculateCompatibilityScore(user)
          const commonInterests = this.findCommonInterests(user)
          const distance = this.calculateDistance(user)
          
          return {
            ...user,
            compatibilityScore: compatibility.score,
            compatibilityDetails: compatibility.details,
            commonInterests,
            distance,
            isOnline: this.checkOnlineStatus(user.lastActive),
            verificationBadges: this.getVerificationBadges(user),
            profileCompleteness: this.calculateProfileCompleteness(user)
          }
        })
        
        // 按兼容性评分排序
        enhancedRecommendations.sort((a, b) => b.compatibilityScore - a.compatibilityScore)
        
        this.setData({
          recommendations: this.data.loadingMore ? 
            [...this.data.recommendations, ...enhancedRecommendations] : 
            enhancedRecommendations,
          loading: false,
          loadingMore: false
        })
        
        // 更新统计信息
        this.updateDiscoveryStats(enhancedRecommendations)
      })
      .catch(error => {
        console.error('加载推荐失败:', error)
        this.setData({ 
          loading: false, 
          loadingMore: false,
          showNoMoreUsers: this.data.recommendations.length === 0
        })
        showError('加载推荐失败，请重试')
      })
  },

  /**
   * 加载更多推荐
   */
  loadMoreRecommendations() {
    if (this.data.loadingMore || this.data.loading) return
    
    this.setData({ loadingMore: true })
    this.loadRecommendations()
  },

  /**
   * 自定义标签页切换
   */
  onCustomTabChange(e) {
    const activeTab = parseInt(e.currentTarget.dataset.tab)
    console.log('📊 标签页切换:', { 
      from: this.data.activeTab, 
      to: activeTab,
      verifiedUsersCount: this.data.verifiedUsers.length 
    })
    
    this.setData({ activeTab })
    
    if (activeTab === 0 && this.data.verifiedUsers.length === 0) {
      // 切换到认证用户标签且没有数据时，加载数据
      console.log('🚀 触发认证用户查询，原因：切换到认证用户标签且数据为空')
      this.loadVerifiedUsers()
    } else if (activeTab === 1 && this.data.recommendations.length === 0) {
      // 切换到未认证用户标签且没有数据时，加载推荐
      console.log('🚀 触发推荐用户查询，原因：切换到未认证用户标签且数据为空')
      this.loadRecommendations()
    }
  },

  /**
   * 标签页切换（兼容原有方法）
   */
  onTabChange(e) {
    const activeTab = e.detail ? e.detail.index : e.currentTarget.dataset.tab
    this.onCustomTabChange({ currentTarget: { dataset: { tab: activeTab } } })
  },

  /**
   * 加载认证用户列表
   */
  loadVerifiedUsers(reset = true) {
    console.log('=== 开始加载认证用户 ===')
    console.log('📋 加载参数:', { reset, loading: this.data.verifiedUsersLoading })
    
    if (this.data.verifiedUsersLoading) {
      console.log('⚠️ 认证用户正在加载中，跳过本次请求')
      return
    }
    
    if (reset) {
      console.log('🔄 重置加载，清空现有数据')
      this.setData({ 
        verifiedUsersPage: 1,
        verifiedUsers: [],
        verifiedUsersLoading: true 
      })
    } else {
      console.log('📄 加载更多数据')
      this.setData({ verifiedUsersLoading: true })
    }
    
    const queryParams = {
      ...this.data.verifiedFilters,
      page: this.data.verifiedUsersPage,
      pageSize: this.data.verifiedUsersPageSize
    }
    
    console.log('📋 原始查询参数:', JSON.stringify(queryParams, null, 2))
    
    // 移除空值
    Object.keys(queryParams).forEach(key => {
      if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === 0) {
        delete queryParams[key]
      }
    })
    
    console.log('🧹 清理后的查询参数:', JSON.stringify(queryParams, null, 2))
    
    // 构建符合API规范的查询参数
    const apiParams = this.buildApiQueryParams(queryParams)
    
    console.log('📋 API查询参数:', JSON.stringify(apiParams, null, 2))
    
    queryUserProfiles(apiParams, {
      showLoading: reset, // 只在重置时显示loading
      loadingTitle: '查询认证用户中...'
    })
      .then(data => {
        // 打印认证用户查询结果
        console.log('=== 认证用户加载结果 ===')
        console.log('📋 查询参数:', JSON.stringify(queryParams, null, 2))
        console.log('📈 API 返回数据:', JSON.stringify(data, null, 2))
        
        const userprofileList = data.userprofileList || []
        const totalNum = data.totalNum || 0
        
        console.log('📊 数据处理:')
        console.log(`  - 原始用户列表长度: ${userprofileList.length}`)
        console.log(`  - 总用户数: ${totalNum}`)
        
        // 处理用户数据，添加需要的字段
        const enhancedUsers = userprofileList.map((user, index) => {
          const enhancedUser = {
            userId: user.userNum,
            userNum: user.userNum,
            name: user.name,
            nickname: user.name, // 使用姓名作为昵称
            gender: user.gender,
            age: user.age || this.calculateAgeFromBirthDate(user.birthDate),
            height: user.height,
            weight: user.weight,
            bmiDesc: user.bmiDesc,
            birthDate: user.birthDate,
            chineseZodiac: user.chineseZodiac,
            maritalStatus: user.maritalStatus,
            education: user.education,
            occupation: user.occupation,
            isPartyMember: user.isPartyMember,
            hometown: user.hometown,
            currentResidence: user.currentResidence,
            assets: user.assets,
            // 为了显示需要，添加默认头像配置
            avatarConfig: this.generateDefaultAvatar(user.gender),
            isVerified: true, // 标记为认证用户
            city: this.extractCityFromResidence(user.currentResidence)
          }
          
          // 打印前3个用户的处理结果
          if (index < 3) {
            console.log(`  处理后的用户 ${index + 1}:`, {
              userId: enhancedUser.userId,
              name: enhancedUser.name,
              gender: enhancedUser.gender,
              age: enhancedUser.age,
              city: enhancedUser.city,
              education: enhancedUser.education,
              occupation: enhancedUser.occupation,
              annualIncome: enhancedUser.assets?.annualIncome,
              isPartyMember: enhancedUser.isPartyMember
            })
          }
          
          return enhancedUser
        })
        
        console.log(`🔄 处理后的用户列表长度: ${enhancedUsers.length}`)
        console.log('=== 认证用户加载结束 ===')
        
        this.setData({
          verifiedUsers: reset ? enhancedUsers : [...this.data.verifiedUsers, ...enhancedUsers],
          verifiedUsersTotal: totalNum,
          verifiedUsersLoading: false,
          verifiedUsersPage: this.data.verifiedUsersPage + (reset ? 0 : 1)
        })
        
        // 打印最终状态
        console.log('📊 最终状态:')
        console.log(`  - 当前页面用户数: ${this.data.verifiedUsers.length}`)
        console.log(`  - 当前页码: ${this.data.verifiedUsersPage}`)
        console.log(`  - 总用户数: ${this.data.verifiedUsersTotal}`)
      })
      .catch(error => {
        console.log('=== 认证用户加载错误 ===')
        console.error('❌ 错误类型:', error.type || 'unknown')
        console.error('❌ 错误消息:', error.message || error)
        console.error('❌ 错误详情:', error)
        console.log('⚠️ 当前查询参数:', JSON.stringify(queryParams, null, 2))
        console.log('=== 认证用户加载错误结束 ===')
        
        this.setData({ verifiedUsersLoading: false })
        showError('加载认证用户失败，请重试')
      })
  },

  /**
   * 加载更多认证用户
   */
  loadMoreVerifiedUsers() {
    console.log('🔄 触发加载更多认证用户')
    console.log('📊 当前状态:', {
      loading: this.data.verifiedUsersLoading,
      currentCount: this.data.verifiedUsers.length,
      totalCount: this.data.verifiedUsersTotal,
      currentPage: this.data.verifiedUsersPage
    })
    
    if (this.data.verifiedUsersLoading || 
        this.data.verifiedUsers.length >= this.data.verifiedUsersTotal) {
      console.log('❌ 无法加载更多: 正在加载中或已加载全部')
      return
    }
    
    this.setData({ verifiedUsersPage: this.data.verifiedUsersPage + 1 })
    this.loadVerifiedUsers(false)
  },

  /**
   * 下拉刷新认证用户列表
   */
  onPullDownRefreshVerifiedUsers() {
    console.log('🔽 下拉刷新认证用户列表')
    
    // 停止下拉刷新动画
    setTimeout(() => {
      this.setData({
        verifiedUsersLoading: false
      })
    }, 1000)
    
    // 重新加载第一页数据
    this.loadVerifiedUsers(true)
  },

  /**
   * 根据生日计算年龄
   */
  calculateAgeFromBirthDate(birthDate) {
    if (!birthDate) return 0
    const today = new Date()
    const birth = new Date(birthDate)
    let age = today.getFullYear() - birth.getFullYear()
    const monthDiff = today.getMonth() - birth.getMonth()
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
      age--
    }
    return age
  },

  /**
   * 生成默认头像配置
   */
  generateDefaultAvatar(gender) {
    if (gender === '男') {
      return {
        type: 'male',
        faceShape: 'square',
        skinTone: 'light',
        hairStyle: 'short_neat',
        eyeStyle: 'confident',
        accessory: 'none',
        clothing: 'formal_shirt',
        expression: 'smile',
        backgroundImage: '/images/avatars/male-bg.svg',
        defaultImage: '/images/avatars/default-male.svg'
      }
    } else {
      return {
        type: 'female', 
        faceShape: 'oval',
        skinTone: 'light',
        hairStyle: 'long_wavy',
        eyeStyle: 'gentle',
        accessory: 'earrings',
        clothing: 'elegant_dress',
        expression: 'sweet_smile',
        backgroundImage: '/images/avatars/female-bg.svg',
        defaultImage: '/images/avatars/default-female.svg'
      }
    }
  },

  /**
   * 从常住地提取城市名称
   */
  extractCityFromResidence(residence) {
    if (!residence) return '未知'
    // 简单提取逻辑，可以根据实际情况调整
    const parts = residence.split('-')
    return parts.length > 1 ? parts[1] : parts[0]
  },

  /**
   * 显示认证用户筛选弹窗
   */
  showVerifiedFilterModal() {
    this.setData({ showVerifiedFilter: true })
  },

  /**
   * 隐藏认证用户筛选弹窗
   */
  hideVerifiedFilterModal() {
    this.setData({ showVerifiedFilter: false })
  },

  /**
   * 应用认证用户筛选
   */
  applyVerifiedFilter() {
    console.log('📋 应用认证用户筛选:')
    console.log('⚙️ 当前筛选条件:', JSON.stringify(this.data.verifiedFilters, null, 2))
    
    try {
      // 验证筛选条件
      const filters = this.data.verifiedFilters
      
      // 验证年龄范围
      if (filters.ageRange.minAge > filters.ageRange.maxAge) {
        showError('最小年龄不能大于最大年龄')
        return
      }
      
      // 验证身高体重
      if (filters.minHeight < 0 || filters.minHeight > 250) {
        showError('请输入正确的身高范围')
        return
      }
      
      if (filters.maxWeight < 0 || filters.maxWeight > 500) {
        showError('请输入正确的体重范围')
        return
      }
      
      // 验证收入
      if (filters.minIncome < 0) {
        showError('最低收入不能为负数')
        return
      }
      
      this.hideVerifiedFilterModal()
      
      // 显示加载状态
      this.setData({ verifiedUsersLoading: true })
      
      // 重新加载数据
      this.loadVerifiedUsers(true)
      
      showSuccess('筛选条件已应用')
    } catch (error) {
      console.error('❌ 应用筛选条件失败:', error)
      showError('应用筛选条件失败，请重试')
    }
  },

  /**
   * 重置认证用户筛选
   */
  resetVerifiedFilter() {
    this.setData({
      verifiedFilters: {
        gender: '',
        ageRange: {
          minAge: 18,
          maxAge: 60
        },
        minHeight: 0,
        maxWeight: 0,
        educationRange: {
          minEducation: '',
          maxEducation: ''
        },
        minIncome: 0,
        occupation: '',
        parentsHasPension: null
      }
    })
    showToast('筛选条件已重置')
  },

  /**
   * 计算兼容性评分
   */
  calculateCompatibilityScore(user) {
    const userProfile = getApp().getUserProfile() || {}
    let totalScore = 0
    const details = {}
    
    // 年龄兼容性 (20%)
    const ageDiff = Math.abs(this.calculateAge(user.birthday) - this.calculateAge(userProfile.birthday))
    const ageScore = Math.max(0, 100 - ageDiff * 5)
    details.age = { score: ageScore, weight: 20 }
    totalScore += ageScore * 0.2
    
    // 兴趣匹配度 (30%)
    const interestScore = this.calculateInterestCompatibility(user, userProfile)
    details.interests = { score: interestScore, weight: 30 }
    totalScore += interestScore * 0.3
    
    // 教育背景匹配 (15%)
    const educationScore = this.calculateEducationCompatibility(user, userProfile)
    details.education = { score: educationScore, weight: 15 }
    totalScore += educationScore * 0.15
    
    // 生活方式匹配 (20%)
    const lifestyleScore = this.calculateLifestyleCompatibility(user, userProfile)
    details.lifestyle = { score: lifestyleScore, weight: 20 }
    totalScore += lifestyleScore * 0.2
    
    // 价值观匹配 (15%)
    const valuesScore = this.calculateValuesCompatibility(user, userProfile)
    details.values = { score: valuesScore, weight: 15 }
    totalScore += valuesScore * 0.15
    
    return {
      score: Math.round(totalScore),
      details
    }
  },

  /**
   * 计算年龄
   */
  calculateAge(birthday) {
    if (!birthday) return 25
    const today = new Date()
    const birthDate = new Date(birthday)
    let age = today.getFullYear() - birthDate.getFullYear()
    const monthDiff = today.getMonth() - birthDate.getMonth()
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--
    }
    return age
  },

  /**
   * 计算兴趣兼容性
   */
  calculateInterestCompatibility(user, userProfile) {
    const userInterests = userProfile.interests || []
    const targetInterests = user.interests || []
    
    if (userInterests.length === 0 || targetInterests.length === 0) {
      return 50 // 默认分数
    }
    
    const commonCount = userInterests.filter(interest => 
      targetInterests.some(target => target.id === interest.id)
    ).length
    
    const totalUnique = new Set([...userInterests.map(i => i.id), ...targetInterests.map(i => i.id)]).size
    
    return Math.round((commonCount / Math.max(userInterests.length, targetInterests.length)) * 100)
  },

  /**
   * 计算教育兼容性
   */
  calculateEducationCompatibility(user, userProfile) {
    const educationLevels = ['highschool', 'college', 'bachelor', 'master', 'doctor']
    const userLevel = educationLevels.indexOf(userProfile.education)
    const targetLevel = educationLevels.indexOf(user.education)
    
    if (userLevel === -1 || targetLevel === -1) return 70
    
    const diff = Math.abs(userLevel - targetLevel)
    return Math.max(50, 100 - diff * 15)
  },

  /**
   * 计算生活方式兼容性
   */
  calculateLifestyleCompatibility(user, userProfile) {
    let score = 70 // 基础分
    
    // 基于兴趣类别分析生活方式
    const userCategories = this.getInterestCategories(userProfile.interests || [])
    const targetCategories = this.getInterestCategories(user.interests || [])
    
    const commonCategories = userCategories.filter(cat => targetCategories.includes(cat))
    
    if (commonCategories.length > 0) {
      score += commonCategories.length * 10
    }
    
    return Math.min(100, score)
  },

  /**
   * 计算价值观兼容性
   */
  calculateValuesCompatibility(user, userProfile) {
    let score = 75 // 基础分
    
    // 基于感情观念
    if (userProfile.relationshipView && user.relationshipView) {
      if (userProfile.relationshipView === user.relationshipView) {
        score += 15
      } else {
        score -= 10
      }
    }
    
    return Math.max(50, Math.min(100, score))
  },

  /**
   * 获取兴趣分类
   */
  getInterestCategories(interests) {
    return [...new Set(interests.map(interest => interest.category))]
  },

  /**
   * 找到共同兴趣
   */
  findCommonInterests(user) {
    const userProfile = getApp().getUserProfile() || {}
    const userInterests = userProfile.interests || []
    const targetInterests = user.interests || []
    
    return userInterests.filter(interest => 
      targetInterests.some(target => target.id === interest.id)
    ).slice(0, 3) // 最多显示3个
  },

  /**
   * 计算距离
   */
  calculateDistance(user) {
    // 模拟距离计算
    return Math.floor(Math.random() * 50) + 1
  },

  /**
   * 检查在线状态
   */
  checkOnlineStatus(lastActive) {
    if (!lastActive) return false
    const now = new Date().getTime()
    const lastActiveTime = new Date(lastActive).getTime()
    return (now - lastActiveTime) < 5 * 60 * 1000 // 5分钟内
  },

  /**
   * 获取认证徽章
   */
  getVerificationBadges(user) {
    const badges = []
    if (user.isRealNameVerified) badges.push('real_name')
    if (user.isEducationVerified) badges.push('education')
    if (user.isWorkVerified) badges.push('work')
    return badges
  },

  /**
   * 计算资料完整度
   */
  calculateProfileCompleteness(user) {
    const fields = ['nickname', 'birthday', 'height', 'education', 'occupation', 'personalStatement', 'avatarConfig']
    const completedFields = fields.filter(field => user[field])
    return Math.round((completedFields.length / fields.length) * 100)
  },

  /**
   * 更新发现统计
   */
  updateDiscoveryStats(recommendations) {
    if (recommendations.length === 0) return
    
    const avgCompatibility = recommendations.reduce((sum, user) => 
      sum + user.compatibilityScore, 0) / recommendations.length
    
    this.setData({
      'discoveryStats.compatibilityAvg': Math.round(avgCompatibility)
    })
  },

  /**
   * 刷新推荐 - 增强版
   */
  refreshRecommendations() {
    this.setData({ 
      recommendations: [],
      currentIndex: 0
    })
    this.loadRecommendations()
    showToast('正在为您找寻新的缘分... 💕')
  },

  /**
   * 切换智能模式
   */
  toggleSmartMode() {
    const newSmartMode = !this.data.smartMode
    this.setData({ smartMode: newSmartMode })
    
    showToast(newSmartMode ? '已开启智能推荐' : '已关闭智能推荐')
    
    // 重新加载推荐
    this.refreshRecommendations()
  },

  /**
   * 上一个用户
   */
  previousUser() {
    const { currentIndex } = this.data
    if (currentIndex > 0) {
      this.setData({ currentIndex: currentIndex - 1 })
    }
  },

  /**
   * 下一个用户
   */
  nextUser() {
    const { currentIndex, recommendations } = this.data
    if (currentIndex < recommendations.length - 1) {
      this.setData({ currentIndex: currentIndex + 1 })
    } else {
      this.loadMoreRecommendations()
    }
  },

  /**
   * 增强的筛选功能
   */
  onDistanceChange(e) {
    this.setData({
      'filters.maxDistance': e.detail.value
    })
  },

  onVerifiedChange(e) {
    this.setData({
      'filters.onlyVerified': e.detail
    })
  },

  onCompatibilityChange(e) {
    this.setData({
      'filters.minCompatibility': e.detail.value
    })
  },

  /**
   * 关闭无更多用户提示
   */
  closeNoMoreUsers() {
    this.setData({ showNoMoreUsers: false })
  },

  /**
   * 调整筛选条件
   */
  adjustFilters() {
    this.showFilterModal()
  },

  /**
   * 显示筛选弹窗
   */
  showFilterModal() {
    this.setData({ showFilter: true })
  },

  /**
   * 隐藏筛选弹窗
   */
  hideFilterModal() {
    this.setData({ showFilter: false })
  },

  /**
   * 年龄范围改变
   */
  onAgeRangeChange(e) {
    this.setData({
      'filters.ageRange': e.detail.value
    })
  },

  /**
   * 身高范围改变
   */
  onHeightRangeChange(e) {
    this.setData({
      'filters.heightRange': e.detail.value
    })
  },

  /**
   * 教育背景改变
   */
  onEducationChange(e) {
    this.setData({
      'filters.education': e.detail.value
    })
  },

  /**
   * 城市改变
   */
  onCityChange(e) {
    this.setData({
      'filters.city': e.detail.value
    })
  },

  /**
   * 城市改变
   */
  onCityChange(e) {
    this.setData({
      'filters.city': e.detail.value
    })
  },

  /**
   * 搜索城市
   */
  searchCity() {
    // TODO: 实现城市搜索功能
    showToast('城市搜索功能开发中')
  },

  /**
   * 重置筛选
   */
  resetFilters() {
    this.setData({
      filters: {
        ageRange: [18, 60],
        heightRange: [150, 200],
        education: [],
        city: ''
      }
    })
  },

  /**
   * 应用筛选
   */
  applyFilters() {
    this.hideFilterModal()
    this.loadRecommendations()
  },

  /**
   * 认证用户性别改变
   */
  onVerifiedGenderChange(e) {
    console.log('👤 性别变更:', e.detail.value)
    this.setData({
      'verifiedFilters.gender': e.detail.value
    })
  },

  /**
   * 认证用户年龄范围改变
   */
  onVerifiedAgeRangeChange(e) {
    console.log('🎂 年龄范围变更:', e.detail.value)
    const [minAge, maxAge] = e.detail.value
    this.setData({
      'verifiedFilters.ageRange.minAge': minAge,
      'verifiedFilters.ageRange.maxAge': maxAge
    })
  },

  /**
   * 认证用户最低身高改变
   */
  onVerifiedMinHeightChange(e) {
    console.log('📏 最低身高变更:', e.detail.value)
    this.setData({
      'verifiedFilters.minHeight': parseInt(e.detail.value) || 0
    })
  },

  /**
   * 认证用户最高体重改变
   */
  onVerifiedMaxWeightChange(e) {
    console.log('⚖️ 最高体重变更:', e.detail.value)
    this.setData({
      'verifiedFilters.maxWeight': parseInt(e.detail.value) || 0
    })
  },

  /**
   * 认证用户教育范围改变
   */
  onVerifiedEducationRangeChange(e) {
    console.log('🎓 教育范围变更:', e)
    const { field, value } = e.currentTarget.dataset
    this.setData({
      [`verifiedFilters.educationRange.${field}`]: value
    })
  },

  /**
   * 认证用户最低收入改变
   */
  onVerifiedMinIncomeChange(e) {
    console.log('💰 最低收入变更:', e.detail.value)
    this.setData({
      'verifiedFilters.minIncome': parseFloat(e.detail.value) || 0
    })
  },

  /**
   * 认证用户职业改变
   */
  onVerifiedOccupationChange(e) {
    console.log('💼 职业变更:', e.detail.value)
    this.setData({
      'verifiedFilters.occupation': e.detail.value
    })
  },

  /**
   * 认证用户父母退休金改变
   */
  onVerifiedParentsPensionChange(e) {
    console.log('🏠 父母退休金变更:', e.detail.value)
    this.setData({
      'verifiedFilters.parentsHasPension': e.detail.value
    })
  },

  /**
   * 选择性别（日系风格）
   */
  selectGender(e) {
    const gender = e.currentTarget.dataset.gender
    this.setData({
      'verifiedFilters.gender': gender
    })
  },

  /**
   * 选择退休金选项（日系风格）
   */
  selectPension(e) {
    const value = e.currentTarget.dataset.value
    this.setData({
      'verifiedFilters.parentsHasPension': value
    })
  },

  // ========== 新增：清新自然风格 UI 事件处理 ==========
  
  /**
   * 切换筛选模式
   */
  switchFilterMode(e) {
    const mode = e.currentTarget.dataset.mode
    console.log('🔄 切换筛选模式:', mode)
    this.setData({ filterMode: mode })
  },
  
  /**
   * 水平滑动开始
   */
  onSwipeStart(e) {
    console.log('👆 滑动开始:', e.touches[0].clientX)
    this.setData({
      swipeStartX: e.touches[0].clientX,
      swiping: true
    })
  },
  
  /**
   * 水平滑动中
   */
  onSwipeMove(e) {
    if (!this.data.swiping) return
    
    const currentX = e.touches[0].clientX
    const diffX = currentX - this.data.swipeStartX
    
    // 限制滑动范围
    const maxTranslate = (this.data.swipeItems.length - 1) * 100
    let newTranslateX = this.data.swipeTranslateX - diffX / 3
    
    if (newTranslateX < 0) newTranslateX = 0
    if (newTranslateX > maxTranslate) newTranslateX = maxTranslate
    
    this.setData({
      swipeTranslateX: newTranslateX,
      swipeStartX: currentX
    })
  },
  
  /**
   * 水平滑动结束
   */
  onSwipeEnd(e) {
    console.log('👆 滑动结束')
    
    if (!this.data.swiping) return
    
    // 计算最近的卡片索引
    const snapIndex = Math.round(this.data.swipeTranslateX / 100)
    const snapTranslateX = snapIndex * 100
    
    this.setData({
      currentSwipeIndex: snapIndex,
      swipeTranslateX: snapTranslateX,
      swiping: false
    })
    
    console.log('📍 卡片定位到:', snapIndex)
  },
  
  /**
   * 点击圆形基础筛选器
   */
  onBasicFilterTap(e) {
    const filterId = e.currentTarget.dataset.id
    console.log('🔴 点击基础筛选器:', filterId)
    
    // 切换激活状态
    const activeFilter = this.data.activeBasicFilter === filterId ? null : filterId
    this.setData({ activeBasicFilter: activeFilter })
    
    // 根据筛选器类型显示不同的设置界面
    this.showBasicFilterOptions(filterId)
  },
  
  /**
   * 显示基础筛选器选项
   */
  showBasicFilterOptions(filterId) {
    switch (filterId) {
      case 'age':
        this.showAgeSelector()
        break
      case 'gender':
        this.showGenderSelector()
        break
      case 'height':
        this.showHeightSelector()
        break
      case 'education':
        this.showEducationSelector()
        break
      case 'income':
        this.showIncomeSelector()
        break
      case 'occupation':
        this.showOccupationSelector()
        break
      default:
        break
    }
  },
  
  /**
   * 显示年龄选择器
   */
  showAgeSelector() {
    wx.showActionSheet({
      itemList: ['18-25岁', '26-30岁', '31-35岁', '36-40岁', '41-50岁', '不限'],
      success: (res) => {
        const ageRanges = [
          { min: 18, max: 25 },
          { min: 26, max: 30 },
          { min: 31, max: 35 },
          { min: 36, max: 40 },
          { min: 41, max: 50 },
          { min: 18, max: 60 }
        ]
        
        const selectedRange = ageRanges[res.tapIndex]
        this.setData({
          'basicFilterValues.age': {
            min: selectedRange.min,
            max: selectedRange.max,
            selected: true
          }
        })
        
        this.applyBasicFilters()
      }
    })
  },
  
  /**
   * 显示性别选择器
   */
  showGenderSelector() {
    wx.showActionSheet({
      itemList: ['男生', '女生', '不限'],
      success: (res) => {
        const genders = ['男', '女', '']
        const selectedGender = genders[res.tapIndex]
        
        this.setData({
          'basicFilterValues.gender': {
            value: selectedGender,
            selected: true
          }
        })
        
        this.applyBasicFilters()
      }
    })
  },
  
  /**
   * 显示身高选择器
   */
  showHeightSelector() {
    wx.showActionSheet({
      itemList: ['155-165cm', '165-175cm', '175-185cm', '185cm以上', '不限'],
      success: (res) => {
        const heightRanges = [
          { min: 155, max: 165 },
          { min: 165, max: 175 },
          { min: 175, max: 185 },
          { min: 185, max: 220 },
          { min: 0, max: 250 }
        ]
        
        const selectedRange = heightRanges[res.tapIndex]
        this.setData({
          'basicFilterValues.height': {
            min: selectedRange.min,
            max: selectedRange.max,
            selected: true
          }
        })
        
        this.applyBasicFilters()
      }
    })
  },
  
  /**
   * 显示学历选择器
   */
  showEducationSelector() {
    wx.showActionSheet({
      itemList: ['高中及以下', '专科', '本科', '硕士', '博士', '不限'],
      success: (res) => {
        const educations = ['高中', '专科', '本科', '硕士', '博士', '']
        const selectedEducation = educations[res.tapIndex]
        
        this.setData({
          'basicFilterValues.education': {
            value: selectedEducation,
            selected: true
          }
        })
        
        this.applyBasicFilters()
      }
    })
  },
  
  /**
   * 显示收入选择器
   */
  showIncomeSelector() {
    wx.showActionSheet({
      itemList: ['5万以下', '5-10万', '10-20万', '20-50万', '50万以上', '不限'],
      success: (res) => {
        const incomes = [0, 5, 10, 20, 50, 0]
        const selectedIncome = incomes[res.tapIndex]
        
        this.setData({
          'basicFilterValues.income': {
            min: selectedIncome,
            selected: true
          }
        })
        
        this.applyBasicFilters()
      }
    })
  },
  
  /**
   * 显示职业选择器
   */
  showOccupationSelector() {
    wx.showActionSheet({
      itemList: ['医生', '教师', '程序员', '金融', '设计师', '其他'],
      success: (res) => {
        const occupations = ['医生', '教师', '程序员', '金融', '设计师', '']
        const selectedOccupation = occupations[res.tapIndex]
        
        this.setData({
          'basicFilterValues.occupation': {
            value: selectedOccupation,
            selected: true
          }
        })
        
        this.applyBasicFilters()
      }
    })
  },
  
  /**
   * 应用基础筛选
   */
  applyBasicFilters() {
    console.log('🔄 应用基础筛选:', this.data.basicFilterValues)
    
    // 将基础筛选转换为 API 参数
    const filters = this.convertBasicFiltersToApiParams()
    
    // 更新认证用户筛选条件
    this.setData({ verifiedFilters: filters })
    
    // 重新加载数据
    this.loadVerifiedUsers(true)
    
    showSuccess('筛选条件已应用')
  },
  
  /**
   * 将基础筛选转换为 API 参数
   */
  convertBasicFiltersToApiParams() {
    const basic = this.data.basicFilterValues
    return {
      gender: basic.gender.selected ? basic.gender.value : '',
      ageRange: {
        minAge: basic.age.selected ? basic.age.min : 18,
        maxAge: basic.age.selected ? basic.age.max : 60
      },
      minHeight: basic.height.selected ? basic.height.min : 0,
      maxWeight: 0, // 基础筛选中不包含体重
      educationRange: {
        minEducation: basic.education.selected ? basic.education.value : '',
        maxEducation: ''
      },
      minIncome: basic.income.selected ? basic.income.min : 0,
      occupation: basic.occupation.selected ? basic.occupation.value : '',
      parentsHasPension: null
    }
  },
  
  /**
   * 显示高级筛选
   */
  showAdvancedFilterModal() {
    console.log('🔧 显示高级筛选')
    this.setData({ showAdvancedFilter: true })
  },
  
  /**
   * 隐藏高级筛选
   */
  hideAdvancedFilterModal() {
    this.setData({ showAdvancedFilter: false })
  },
  
  /**
   * 清除所有筛选
   */
  clearAllFilters() {
    console.log('🧹 清除所有筛选')
    
    this.setData({
      activeBasicFilter: null,
      basicFilterValues: {
        age: { min: 18, max: 35, selected: false },
        gender: { value: '', selected: false },
        height: { min: 160, max: 180, selected: false },
        education: { value: '', selected: false },
        income: { min: 0, selected: false },
        occupation: { value: '', selected: false },
      },
      verifiedFilters: {
        gender: '',
        ageRange: { minAge: 18, maxAge: 60 },
        minHeight: 0,
        maxWeight: 0,
        educationRange: { minEducation: '', maxEducation: '' },
        minIncome: 0,
        occupation: '',
        parentsHasPension: null
      }
    })
    
    // 重新加载数据
    this.loadVerifiedUsers(true)
    
    showSuccess('筛选条件已清除')
  },

  /**
   * 认证用户教育改变（简化版）
   */
  onVerifiedEducationChange(e) {
    console.log('🎓 教育背景变更:', e.detail.value)
    this.setData({
      'verifiedFilters.educationRange.minEducation': e.detail.value
    })
  },

  /**
   * 处理认证用户喜欢
   */
  handleVerifiedUserLike(e) {
    e.stopPropagation() // 阻止事件冒泡，防止触发用户详情
    
    const userId = e.currentTarget.dataset.userId
    if (!userId) return
    
    post('/api/discovery/like', { 
      userId: userId,
      source: 'verified_users' // 标记来源为认证用户列表
    })
      .then(data => {
        showToast('已发送喜欢 💕')
        
        if (data.isMatch) {
          // 匹配成功，显示匹配成功弹窗
          const matchedUser = this.data.verifiedUsers.find(user => user.userNum === userId)
          this.setData({
            showMatchSuccess: true,
            matchedUser: matchedUser
          })
        }
      })
      .catch(error => {
        console.error('发送喜欢失败:', error)
        showError('发送喜欢失败，请重试')
      })
  },

  // 触摸事件处理 - 增强版
  onTouchStart(e) {
    this.setData({
      touchStartX: e.touches[0].clientX,
      touchStartY: e.touches[0].clientY,
      isDragging: true
    })
  },

  onTouchMove(e) {
    if (!this.data.isDragging) return
    
    const { touchStartX, touchStartY } = this.data
    const currentX = e.touches[0].clientX
    const currentY = e.touches[0].clientY
    const deltaX = currentX - touchStartX
    const deltaY = currentY - touchStartY
    
    // 防止垂直滚动时触发水平滑动
    if (Math.abs(deltaY) > Math.abs(deltaX)) {
      return
    }
    
    // 计算旋转角度和透明度
    const rotation = deltaX * 0.1
    const opacity = 1 - Math.abs(deltaX) / 300
    
    // 设置卡片变换
    const transform = `translateX(${deltaX}px) rotate(${rotation}deg)`
    this.setData({
      cardTransform: transform,
      swipeDirection: deltaX > 50 ? 'right' : deltaX < -50 ? 'left' : ''
    })
  },

  onTouchEnd(e) {
    if (!this.data.isDragging) return
    
    const { touchStartX } = this.data
    const currentX = e.changedTouches[0].clientX
    const deltaX = currentX - touchStartX
    
    // 重置状态
    this.setData({ 
      isDragging: false,
      cardTransform: '',
      swipeDirection: ''
    })
    
    // 判断滑动距离
    if (Math.abs(deltaX) > 120) {
      const index = this.data.currentIndex
      const user = this.data.recommendations[index]
      
      if (user) {
        if (deltaX > 0) {
          // 右滑：喜欢
          this.handleLike(null, index, user.userId)
        } else {
          // 左滑：跳过
          this.handleSkip(null, index, user.userId)
        }
      }
    }
  },

  /**
   * Super Like 功能
   */
  handleSuperLike(e) {
    if (this.data.superLikesRemaining <= 0) {
      showError('今日 Super Like 次数已用完')
      return
    }
    
    const index = e.currentTarget.dataset.index || this.data.currentIndex
    const user = this.data.recommendations[index]
    
    if (!user) return
    
    post('/api/discovery/super-like', { userId: user.userId })
      .then(data => {
        this.setData({
          superLikesRemaining: this.data.superLikesRemaining - 1,
          showSuperLikeSuccess: true
        })
        
        this.removeCard(index)
        
        // 延迟隐藏成功提示
        setTimeout(() => {
          this.setData({ showSuperLikeSuccess: false })
        }, 2000)
        
        if (data.isMatch) {
          this.setData({
            showMatchSuccess: true,
            matchedUser: user
          })
        }
      })
      .catch(error => {
        console.error('Super Like 失败:', error)
        showError('Super Like 发送失败')
      })
  },

  /**
   * 处理喜欢 - 增强版
   */
  handleLike(e, cardIndex, userId) {
    const index = cardIndex !== undefined ? cardIndex : this.data.currentIndex
    const user = this.data.recommendations[index]
    
    if (!user) return
    
    const targetUserId = userId || user.userId
    
    // 更新本地计数
    this.setData({
      todayLikes: this.data.todayLikes + 1,
      'discoveryStats.totalLikes': this.data.discoveryStats.totalLikes + 1
    })
    
    post('/api/discovery/like', { 
      userId: targetUserId,
      compatibilityScore: user.compatibilityScore,
      commonInterests: user.commonInterests?.map(i => i.id) || []
    })
      .then(data => {
        this.removeCard(index)
        
        if (data.isMatch) {
          // 匹配成功
          this.setData({
            showMatchSuccess: true,
            matchedUser: user,
            'discoveryStats.totalMatches': this.data.discoveryStats.totalMatches + 1
          })
        } else {
          showToast('已发送喜欢 💕')
        }
        
        // 检查是否需要显示反馈
        this.checkShowFeedback()
      })
      .catch(error => {
        console.error('发送喜欢失败:', error)
        // 回滚本地计数
        this.setData({
          todayLikes: this.data.todayLikes - 1,
          'discoveryStats.totalLikes': this.data.discoveryStats.totalLikes - 1
        })
        showError('操作失败，请重试')
      })
  },

  /**
   * 处理跳过 - 增强版
   */
  handleSkip(e, cardIndex, userId) {
    const index = cardIndex !== undefined ? cardIndex : this.data.currentIndex
    const user = this.data.recommendations[index]
    
    if (!user) return
    
    const targetUserId = userId || user.userId
    
    // 更新本地计数
    this.setData({
      todaySkips: this.data.todaySkips + 1
    })
    
    post('/api/discovery/skip', { 
      userId: targetUserId,
      reason: 'swipe_left', // 跳过原因
      compatibilityScore: user.compatibilityScore
    })
      .then(() => {
        this.removeCard(index)
      })
      .catch(error => {
        console.error('跳过失败:', error)
        // 回滚本地计数
        this.setData({
          todaySkips: this.data.todaySkips - 1
        })
        showError('操作失败，请重试')
      })
  },

  /**
   * 移除卡片 - 增强版
   */
  removeCard(index) {
    const { recommendations, currentIndex } = this.data
    
    // 移除指定卡片
    recommendations.splice(index, 1)
    
    // 更新当前索引
    let newCurrentIndex = currentIndex
    if (index <= currentIndex && currentIndex > 0) {
      newCurrentIndex = currentIndex - 1
    }
    
    this.setData({ 
      recommendations,
      currentIndex: Math.min(newCurrentIndex, recommendations.length - 1)
    })
    
    // 如果推荐列表少于5个，加载更多
    if (recommendations.length < 5) {
      this.loadMoreRecommendations()
    }
    
    // 如果没有更多用户
    if (recommendations.length === 0) {
      this.setData({ showNoMoreUsers: true })
    }
  },

  /**
   * 检查是否显示反馈
   */
  checkShowFeedback() {
    const { todayLikes, todaySkips } = this.data
    const totalActions = todayLikes + todaySkips
    
    // 每10个操作显示一次反馈
    if (totalActions > 0 && totalActions % 10 === 0) {
      this.setData({
        showFeedback: true,
        feedbackType: 'quality'
      })
    }
  },

  /**
   * 提交反馈
   */
  submitFeedback(e) {
    const rating = e.currentTarget.dataset.rating
    
    post('/api/discovery/feedback', {
      rating: rating,
      type: this.data.feedbackType,
      totalLikes: this.data.todayLikes,
      totalSkips: this.data.todaySkips
    })
      .then(() => {
        this.setData({ showFeedback: false })
        showSuccess('谢谢您的反馈！')
      })
      .catch(error => {
        console.error('反馈失败:', error)
        this.setData({ showFeedback: false })
      })
  },

  /**关闭反馈弹窗 */
  closeFeedback() {
    this.setData({ showFeedback: false })
  },

  /**
   * 显示用户详情
   */
  showUserDetail(e) {
    // 检查是否是认证用户列表中的用户
    const userData = e.currentTarget.dataset.user
    let userNum, sourceUser
    
    if (userData) {
      // 认证用户列表中的用户
      userNum = userData.userNum
      sourceUser = userData
    } else {
      // 推荐列表中的用户
      const index = parseInt(e.currentTarget.dataset.index)
      const user = this.data.recommendations[index]
      if (!user) return
      userNum = user.userId
      sourceUser = user
    }
    
    console.log('👥 点击查看用户详情:', {
      userNum: userNum,
      source: userData ? '认证用户列表' : '推荐列表',
      name: sourceUser.name || sourceUser.nickname
    })
    
    // 调用 API 获取用户详细信息
    queryUserAllInfo([userNum])
      .then(data => {
        console.log('✅ 获取用户详情成功:', data)
        
        if (data && data.userInfoList && data.userInfoList.length > 0) {
          const detailedUser = data.userInfoList[0]
          
          // 合并原有的用户信息和详细信息
          const enhancedUser = {
            ...sourceUser,
            ...detailedUser,
            // 保留原有的头像配置
            avatarConfig: sourceUser.avatarConfig || this.generateDefaultAvatar(detailedUser.gender),
            // 添加详细信息标识
            hasDetailedInfo: true,
            // 统一 ID 字段
            userId: detailedUser.userNum,
            nickname: detailedUser.name
          }
          
          console.log('📝 合并后的用户信息:', {
            userNum: enhancedUser.userNum,
            name: enhancedUser.name,
            gender: enhancedUser.gender,
            age: enhancedUser.age,
            education: enhancedUser.education,
            occupation: enhancedUser.occupation,
            assets: enhancedUser.assets,
            requirements: {
              ageRange: enhancedUser.ageRange,
              minHeight: enhancedUser.minHeight,
              maxWeight: enhancedUser.maxWeight,
              minIncome: enhancedUser.minIncome
            }
          })
          
          this.setData({
            showUserDetail: true,
            selectedUser: enhancedUser
          })
        } else {
          console.warn('⚠️ API 返回数据为空，使用基本信息显示详情')
          this.setData({
            showUserDetail: true,
            selectedUser: sourceUser
          })
        }
      })
      .catch(error => {
        console.error('❌ 获取用户详情失败:', error)
        showError('获取用户详情失败，显示基本信息')
        
        // 失败时使用基本信息显示详情
        this.setData({
          showUserDetail: true,
          selectedUser: sourceUser
        })
      })
  },

  /**
   * 隐藏用户详情
   */
  hideUserDetail() {
    this.setData({
      showUserDetail: false,
      selectedUser: null
    })
  },

  /**
   * 从详情页跳过
   */
  handleSkipFromDetail() {
    const { selectedUser, recommendations } = this.data
    const index = recommendations.findIndex(user => user.userId === selectedUser.userId)
    
    this.hideUserDetail()
    this.handleSkip(null, index, selectedUser.userId)
  },

  /**
   * 从详情页喜欢
   */
  handleLikeFromDetail() {
    const { selectedUser, recommendations } = this.data
    const index = recommendations.findIndex(user => user.userId === selectedUser.userId)
    
    this.hideUserDetail()
    this.handleLike(null, index, selectedUser.userId)
  },

  /**
   * 隐藏匹配成功弹窗
   */
  hideMatchSuccess() {
    this.setData({
      showMatchSuccess: false,
      matchedUser: null
    })
  },

  /**
   * 继续滑动
   */
  continueSwiping() {
    this.hideMatchSuccess()
  },

  /**
   * 开始聊天
   */
  startChat() {
    const { matchedUser } = this.data
    this.hideMatchSuccess()
    
    // 跳转到聊天页面
    navigateTo(`/pages/chat/chat?userId=${matchedUser.userId}`)
  },

  /**
   * 分享页面
   */
  onShareAppMessage() {
    return {
      title: '青鸟笺 - 用心灵相遇，让真爱绽放',
      path: '/pages/discovery/discovery',
      imageUrl: '../../images/share-discovery.png'
    }
  },

  // =====================================
  // 新鲜自然UI - 高级筛选功能
  // =====================================

  /**
   * 显示高级筛选
   */
  showAdvancedFilters() {
    console.log('🔧 显示高级筛选面板')
    this.setData({ showAdvancedFilters: true })
  },

  /**
   * 隐藏高级筛选
   */
  hideAdvancedFilters() {
    console.log('🔧 隐藏高级筛选面板')
    this.setData({ showAdvancedFilters: false })
  },

  /**
   * 选择性别
   */
  selectFreshGender(e) {
    const gender = e.currentTarget.dataset.gender
    console.log('👫 选择性别:', gender)
    
    this.setData({
      'freshFilters.gender': gender
    })
  },

  /**
   * 年龄范围变化
   */
  onFreshAgeRangeChange(e) {
    const [minAge, maxAge] = e.detail.value
    console.log('🎂 年龄范围变化:', { minAge, maxAge })
    
    this.setData({
      'freshFilters.ageRange.min': minAge,
      'freshFilters.ageRange.max': maxAge
    })
  },

  /**
   * 最低身高变化
   */
  onFreshMinHeightChange(e) {
    const minHeight = parseInt(e.detail.value) || 0
    console.log('📏 最低身高变化:', minHeight)
    
    this.setData({
      'freshFilters.heightRange.min': minHeight
    })
  },

  /**
   * 最高体重变化
   */
  onFreshMaxWeightChange(e) {
    const maxWeight = parseInt(e.detail.value) || 0
    console.log('⚖️ 最高体重变化:', maxWeight)
    
    this.setData({
      'freshFilters.maxWeight': maxWeight
    })
  },

  /**
   * 学历变化
   */
  onFreshEducationChange(e) {
    const education = this.data.freshEducationOptions[e.detail.value] || ''
    console.log('🎓 学历变化:', education)
    
    this.setData({
      'freshFilters.education': education
    })
  },

  /**
   * 最低收入变化
   */
  onFreshMinIncomeChange(e) {
    const minIncome = parseInt(e.detail.value) || 0
    console.log('💰 最低收入变化:', minIncome)
    
    this.setData({
      'freshFilters.minIncome': minIncome
    })
  },

  /**
   * 职业变化
   */
  onFreshOccupationChange(e) {
    const occupation = e.detail.value
    console.log('💼 职业变化:', occupation)
    
    this.setData({
      'freshFilters.occupation': occupation
    })
  },

  /**
   * 地区变化
   */
  onFreshLocationChange(e) {
    const location = e.detail.value
    console.log('📍 地区变化:', location)
    
    this.setData({
      'freshFilters.location': location
    })
  },

  /**
   * 选择养老金情况
   */
  selectFreshPension(e) {
    const value = e.currentTarget.dataset.value
    const parentsHasPension = value === 'null' ? null : value === 'true'
    console.log('🏠 选择养老金情况:', parentsHasPension)
    
    this.setData({
      'freshFilters.parentsHasPension': parentsHasPension
    })
  },

  /**
   * 重置清新筛选
   */
  resetFreshFilters() {
    console.log('🔄 重置清新筛选')
    
    const defaultFilters = {
      gender: '',
      ageRange: { min: 18, max: 35 },
      heightRange: { min: 150, max: 185 },
      maxWeight: 0,
      education: '',
      minIncome: 0,
      occupation: '',
      location: '',
      parentsHasPension: null,
      activeBasicFilter: ''
    }
    
    this.setData({ freshFilters: defaultFilters })
    showSuccess('筛选条件已重置')
  },

  /**
   * 应用清新筛选
   */
  applyFreshFilters() {
    console.log('🔍 应用清新筛选:', this.data.freshFilters)
    
    // 隐藏高级筛选面板
    this.hideAdvancedFilters()
    
    // 开始搜索
    this.searchWithFilters()
  },

  /**
   * 使用筛选条件搜索
   */
  searchWithFilters() {
    console.log('🔍 开始按筛选条件搜索')
    console.log('📝 当前筛选条件:', JSON.stringify(this.data.freshFilters, null, 2))
    
    // 将清新筛选条件转换为认证用户筛选格式
    const convertedFilters = this.convertFreshFiltersToVerified(this.data.freshFilters)
    
    console.log('🔄 转换后的筛选条件:', JSON.stringify(convertedFilters, null, 2))
    
    // 更新认证用户筛选条件
    this.setData({ verifiedFilters: convertedFilters })
    
    // 重新加载认证用户数据
    this.loadVerifiedUsers(true)
    
    showSuccess('正在按您的条件搜索...')
  },

  /**
   * 将清新筛选条件转换为认证用户筛选格式
   */
  convertFreshFiltersToVerified(freshFilters) {
    const converted = {
      gender: freshFilters.gender || '',
      ageRange: {
        minAge: freshFilters.ageRange.min,
        maxAge: freshFilters.ageRange.max
      },
      minHeight: freshFilters.heightRange.min || 0,
      maxWeight: freshFilters.maxWeight || 0,
      educationRange: {
        minEducation: freshFilters.education || ''
      },
      minIncome: freshFilters.minIncome || 0,
      occupation: freshFilters.occupation || '',
      parentsHasPension: freshFilters.parentsHasPension
    }
    
    console.log('🔄 筛选条件转换结果:', {
      '源条件': freshFilters,
      '目标条件': converted
    })
    
    return converted
  },

  // =====================================
  // 精致筛选系统 - 参考设计
  // =====================================

  /**
   * 切换精致筛选标签页
   */
  switchRefinedTab(e) {
    const tab = e.currentTarget.dataset.tab
    console.log('🔄 切换精致筛选标签页:', tab)
    
    this.setData({ refinedActiveTab: tab })
  },

  /**
   * 选择精致筛选条件
   */
  selectRefinedFilter(e) {
    const { type, value } = e.currentTarget.dataset
    console.log('🏷️ 选择精致筛选:', { type, value })
    
    const currentValue = this.data.refinedFilters[type]
    let newValue
    
    // 处理不同类型的值
    if (type === 'minHeight') {
      newValue = currentValue === parseInt(value) ? 0 : parseInt(value)
    } else if (type === 'hasHouse' || type === 'isPartyMember' || type === 'hasProperty' || type === 'wantsBaby') {
      newValue = currentValue === (value === 'true') ? null : (value === 'true')
    } else {
      newValue = currentValue === value ? '' : value
    }
    
    this.setData({
      [`refinedFilters.${type}`]: newValue
    })
    
    console.log('📝 更新后的筛选条件:', this.data.refinedFilters)
  },

  /**
   * 重置精致筛选
   */
  resetRefinedFilters() {
    console.log('🔄 重置精致筛选')
    
    const defaultFilters = {
      gender: '',
      occupation: '',
      minHeight: 0,
      location: '',
      hasHouse: null,
      experience: '',
      isPartyMember: null,
      locationAlt: '',
      hasProperty: null,
      personality: '',
      maritalStatus: '',
      wantsBaby: null,
      ageRange: { min: 18, max: 35 },
      heightRange: { min: 150, max: 185 },
      education: '',
      minIncome: 0
    }
    
    this.setData({ refinedFilters: defaultFilters })
    showSuccess('筛选条件已重置')
  },

  /**
   * 应用精致筛选
   */
  applyRefinedFilters() {
    console.log('🔍 应用精致筛选:', this.data.refinedFilters)
    
    // 检查是否有选中的筛选条件
    const hasActiveFilters = this.checkHasActiveRefinedFilters()
    
    if (!hasActiveFilters) {
      showError('请选择至少一个筛选条件')
      return
    }
    
    // 将精致筛选条件转换为认证用户筛选格式
    const convertedFilters = this.convertRefinedFiltersToVerified(this.data.refinedFilters)
    
    console.log('🔄 转换后的筛选条件:', JSON.stringify(convertedFilters, null, 2))
    
    // 更新认证用户筛选条件
    this.setData({ verifiedFilters: convertedFilters })
    
    // 重新加载认证用户数据
    this.loadVerifiedUsers(true)
    
    showSuccess('正在按您的条件搜索...')
  },

  /**
   * 检查是否有激活的精致筛选条件
   */
  checkHasActiveRefinedFilters() {
    const filters = this.data.refinedFilters
    
    return filters.gender !== '' ||
           filters.occupation !== '' ||
           filters.minHeight > 0 ||
           filters.location !== '' ||
           filters.hasHouse !== null ||
           filters.experience !== '' ||
           filters.isPartyMember !== null ||
           filters.locationAlt !== '' ||
           filters.hasProperty !== null ||
           filters.personality !== '' ||
           filters.maritalStatus !== '' ||
           filters.wantsBaby !== null ||
           filters.education !== '' ||
           filters.minIncome > 0
  },

  /**
   * 构建API查询参数
   */
  buildApiQueryParams(queryParams = {}) {
    const filters = this.data.verifiedFilters
    
    // 构建符合API规范的参数
    const apiParams = {
      pageNum: this.data.verifiedUsersPage,
      pageSize: this.data.verifiedUsersPageSize
    }
    
    // 性别筛选
    if (filters.gender) {
      apiParams.gender = filters.gender
    }
    
    // 年龄范围
    if (filters.ageRange && (filters.ageRange.minAge || filters.ageRange.maxAge)) {
      apiParams.ageRange = {
        minAge: filters.ageRange.minAge || 18,
        maxAge: filters.ageRange.maxAge || 60
      }
    }
    
    // 身高要求
    if (filters.minHeight && filters.minHeight > 0) {
      apiParams.heightRange = {
        minHeight: filters.minHeight
      }
    }
    
    // 体重要求
    if (filters.maxWeight && filters.maxWeight > 0) {
      apiParams.weightRange = {
        maxWeight: filters.maxWeight
      }
    }
    
    // 学历要求
    if (filters.educationRange && filters.educationRange.minEducation) {
      apiParams.educationRange = {
        minEducation: filters.educationRange.minEducation
      }
    }
    
    // 收入要求
    if (filters.minIncome && filters.minIncome > 0) {
      apiParams.incomeRange = {
        minIncome: filters.minIncome
      }
    }
    
    // 职业
    if (filters.occupation) {
      apiParams.occupation = filters.occupation
    }
    
    // 父母退休金
    if (filters.parentsHasPension !== null) {
      apiParams.parentsHasPension = filters.parentsHasPension
    }
    
    return apiParams
  },

  /**
   * 将精致筛选条件转换为认证用户筛选格式
   */
  convertRefinedFiltersToVerified(refinedFilters) {
    const converted = {
      gender: refinedFilters.gender || '',
      ageRange: {
        minAge: refinedFilters.ageRange.min,
        maxAge: refinedFilters.ageRange.max
      },
      minHeight: refinedFilters.minHeight || 0,
      maxWeight: 0,
      educationRange: {
        minEducation: refinedFilters.education || ''
      },
      minIncome: refinedFilters.minIncome || 0,
      occupation: refinedFilters.occupation || '',
      parentsHasPension: refinedFilters.isPartyMember
    }
    
    console.log('🔄 精致筛选条件转换结果:', {
      '源条件': refinedFilters,
      '目标条件': converted
    })
    
    return converted
  },

  // ========== 条件查找功能 ==========

  /**
   * 切换查找模式
   */
  switchSearchMode(e) {
    const mode = e.currentTarget.dataset.mode
    console.log('🔄 切换查找模式:', mode)
    this.setData({ searchMode: mode })
  },

  /**
   * 选择普通筛选条件
   */
  selectSimpleFilter(e) {
    const { type, value } = e.currentTarget.dataset
    console.log('🏷️ 选择普通筛选:', { type, value })
    
    const currentValue = this.data.simpleFilters[type]
    let newValue
    
    if (type === 'minHeight') {
      newValue = currentValue === parseInt(value) ? 0 : parseInt(value)
    } else {
      newValue = currentValue === value ? '' : value
    }
    
    this.setData({
      [`simpleFilters.${type}`]: newValue
    })
  },

  /**
   * 重置普通筛选
   */
  resetSimpleFilters() {
    console.log('🔄 重置普通筛选')
    this.setData({
      simpleFilters: {
        occupation: '',
        minHeight: 0,
        city: ''
      }
    })
    showToast('筛选条件已重置')
  },

  /**
   * 开始普通查找
   */
  startSimpleSearch() {
    console.log('🔍 开始普通查找:', this.data.simpleFilters)
    
    // 检查是否有选中的筛选条件
    const hasFilters = this.data.simpleFilters.occupation || 
                      this.data.simpleFilters.minHeight > 0 || 
                      this.data.simpleFilters.city
    
    if (!hasFilters) {
      showError('请选择至少一个筛选条件')
      return
    }
    
    this.performSearch(this.data.simpleFilters)
  },

  /**
   * 高级筛选年龄范围改变
   */
  onAdvancedAgeRangeChange(e) {
    this.setData({
      'advancedFilters.ageRange': e.detail.value
    })
  },

  /**
   * 高级筛选身高范围改变
   */
  onAdvancedHeightRangeChange(e) {
    this.setData({
      'advancedFilters.heightRange': e.detail.value
    })
  },

  /**
   * 高级筛选教育背景改变
   */
  onAdvancedEducationChange(e) {
    this.setData({
      'advancedFilters.education': e.detail.value
    })
  },

  /**
   * 高级筛选职业改变
   */
  onAdvancedOccupationChange(e) {
    this.setData({
      'advancedFilters.occupation': e.detail.value
    })
  },

  /**
   * 高级筛选收入改变
   */
  onAdvancedIncomeChange(e) {
    this.setData({
      'advancedFilters.income': e.detail.value
    })
  },

  /**
   * 高级筛选兴趣改变
   */
  onAdvancedInterestsChange(e) {
    this.setData({
      'advancedFilters.interests': e.detail.value
    })
  },

  /**
   * 高级筛选距离改变
   */
  onAdvancedDistanceChange(e) {
    this.setData({
      'advancedFilters.maxDistance': e.detail.value
    })
  },

  /**
   * 高级筛选认证用户开关改变
   */
  onAdvancedVerifiedChange(e) {
    this.setData({
      'advancedFilters.onlyVerified': e.detail
    })
  },

  /**
   * 高级筛选党员要求开关改变
   */
  onAdvancedPartyMemberChange(e) {
    this.setData({
      'advancedFilters.onlyPartyMember': e.detail
    })
  },

  /**
   * 重置高级筛选
   */
  resetAdvancedFilters() {
    console.log('🔄 重置高级筛选')
    this.setData({
      advancedFilters: {
        ageRange: [18, 35],
        heightRange: [150, 185],
        education: [],
        occupation: '',
        income: '0',
        interests: [],
        maxDistance: 50,
        onlyVerified: false
      }
    })
    showToast('筛选条件已重置')
  },

  /**
   * 开始高级查找
   */
  startAdvancedSearch() {
    console.log('🔍 开始高级查找:', this.data.advancedFilters)
    
    // 检查是否有选中的筛选条件
    const filters = this.data.advancedFilters
    const hasFilters = filters.education.length > 0 || 
                      filters.occupation || 
                      filters.income !== '0' || 
                      filters.interests.length > 0 || 
                      filters.onlyVerified
    
    if (!hasFilters) {
      showError('请选择至少一个筛选条件')
      return
    }
    
    this.performSearch(filters)
  },

  /**
   * 执行搜索
   */
  performSearch(filters) {
    console.log('🔍 执行搜索:', filters)
    
    this.setData({ 
      searchLoading: true,
      searchResults: [],
      searchPage: 1
    })
    
    // 将简单筛选条件转换为API参数格式
    const apiParams = this.convertSimpleFiltersToApiParams(filters)
    apiParams.pageNum = 1
    apiParams.pageSize = 20
    
    console.log('🔍 搜索API参数:', JSON.stringify(apiParams, null, 2))
    
    // 调用用户档案查询API
    queryUserProfiles(apiParams, {
      showLoading: false, // 已经有自己的loading状态
      loadingTitle: '搜索用户中...'
    })
      .then(data => {
        const userprofileList = data.userprofileList || []
        const totalNum = data.totalNum || 0
        
        console.log('🔍 搜索结果:', { count: userprofileList.length, total: totalNum })
        
        // 处理搜索结果，转换为页面显示格式
        const enhancedUsers = userprofileList.map((user, index) => {
          const enhancedUser = {
            userId: user.userNum,
            userNum: user.userNum,
            name: user.name,
            nickname: user.name,
            gender: user.gender,
            age: user.age || this.calculateAgeFromBirthDate(user.birthDate),
            height: user.height,
            weight: user.weight,
            education: user.education,
            occupation: user.occupation,
            city: this.extractCityFromResidence(user.currentResidence),
            currentResidence: user.currentResidence,
            maritalStatus: user.maritalStatus,
            assets: user.assets,
            isPartyMember: user.isPartyMember,
            avatarConfig: this.generateDefaultAvatar(user.gender),
            isVerified: true, // 搜索结果都是认证用户
            compatibilityScore: 75 + Math.floor(Math.random() * 20) // 模拟匹配度
          }
          
          return enhancedUser
        })
        
        this.setData({
          searchResults: enhancedUsers,
          searchTotal: totalNum,
          searchLoading: false
        })
        
        if (enhancedUsers.length === 0) {
          showToast('未找到符合条件的用户')
        } else {
          showSuccess(`找到 ${totalNum} 位用户`)
        }
      })
      .catch(error => {
        console.error('搜索失败:', error)
        this.setData({ searchLoading: false })
        showError('搜索失败，请重试')
      })
  },

  /**
   * 将简单筛选条件转换为API参数格式
   */
  convertSimpleFiltersToApiParams(filters) {
    const apiParams = {}
    
    // 职业筛选
    if (filters.occupation) {
      apiParams.occupation = filters.occupation
    }
    
    // 身高筛选
    if (filters.minHeight && filters.minHeight > 0) {
      apiParams.heightRange = {
        minHeight: filters.minHeight
      }
    }
    
    // 城市筛选 - 转换为工作地要求
    if (filters.city) {
      apiParams.currentResidencePreference = [filters.city]
    }
    
    return apiParams
  },

  /**
   * 加载更多搜索结果
   */
  loadMoreSearchResults() {
    if (this.data.searchLoading || 
        this.data.searchResults.length >= this.data.searchTotal) {
      return
    }
    
    this.setData({ 
      searchLoading: true,
      searchPage: this.data.searchPage + 1
    })
    
    // 构建搜索参数
    const filters = this.data.searchMode === 'simple' ? 
                   this.data.simpleFilters : 
                   this.data.advancedFilters
    
    const searchParams = {
      ...filters,
      page: this.data.searchPage,
      pageSize: 20
    }
    
    get('/api/discovery/search', searchParams)
      .then(data => {
        const users = data.users || []
        
        const enhancedUsers = users.map(user => ({
          ...user,
          compatibilityScore: this.calculateCompatibilityScore(user).score,
          isVerified: user.isRealNameVerified || user.isEducationVerified || user.isWorkVerified
        }))
        
        this.setData({
          searchResults: [...this.data.searchResults, ...enhancedUsers],
          searchLoading: false
        })
      })
      .catch(error => {
        console.error('加载更多搜索结果失败:', error)
        this.setData({ searchLoading: false })
        showError('加载失败，请重试')
      })
  },

  /**
   * 搜索结果用户点赞
   */
  handleSearchResultLike(e) {
    const userId = e.currentTarget.dataset.userId
    console.log('❤️ 搜索结果用户点赞:', userId)
    
    // 调用点赞API
    post('/api/user/like', { targetUserId: userId })
      .then(data => {
        if (data.isMatch) {
          // 匹配成功
          this.showMatchSuccess(data.matchedUser)
        } else {
          showSuccess('已表达喜欢')
        }
      })
      .catch(error => {
        console.error('点赞失败:', error)
        showError('操作失败，请重试')
      })
  },

  /**
   * 显示排序选项
   */
  showSortOptions() {
    wx.showActionSheet({
      itemList: ['按匹配度排序', '按年龄排序', '按距离排序', '按活跃度排序'],
      success: (res) => {
        const sortTypes = ['compatibility', 'age', 'distance', 'activity']
        const sortType = sortTypes[res.tapIndex]
        this.sortSearchResults(sortType)
      }
    })
  },

  /**
   * 排序搜索结果
   */
  sortSearchResults(sortType) {
    console.log('📊 排序搜索结果:', sortType)
    
    const results = [...this.data.searchResults]
    
    switch (sortType) {
      case 'compatibility':
        results.sort((a, b) => (b.compatibilityScore || 0) - (a.compatibilityScore || 0))
        break
      case 'age':
        results.sort((a, b) => (a.age || 0) - (b.age || 0))
        break
      case 'distance':
        results.sort((a, b) => (a.distance || 0) - (b.distance || 0))
        break
      case 'activity':
        results.sort((a, b) => new Date(b.lastActive || 0) - new Date(a.lastActive || 0))
        break
    }
    
    this.setData({ searchResults: results })
    showToast('排序完成')
  },

  // ========== 用户交互相关方法 ==========



  /**
   * 从详情页点赞
   */
  handleLikeFromDetail(e) {
    const userId = e.currentTarget.dataset.userId
    console.log('❤️ 从详情页点赞:', userId)
    
    this.handleLike({ currentTarget: { dataset: { userId } } })
    this.hideUserDetail()
  },

  /**
   * 处理点赞
   */
  handleLike(e) {
    const userId = e.currentTarget.dataset.userId
    console.log('❤️ 用户点赞:', userId)
    
    // 调用点赞API
    post('/api/user/like', { targetUserId: userId })
      .then(data => {
        if (data.isMatch) {
          // 匹配成功
          this.showMatchSuccess(data.matchedUser)
        } else {
          showSuccess('已表达喜欢')
        }
        
        // 从推荐列表中移除该用户
        this.removeUserFromRecommendations(userId)
      })
      .catch(error => {
        console.error('点赞失败:', error)
        showError('操作失败，请重试')
      })
  },

  /**
   * 处理跳过
   */
  handleSkip(e) {
    const userId = e.currentTarget.dataset.userId
    console.log('⏭️ 用户跳过:', userId)
    
    // 从推荐列表中移除该用户
    this.removeUserFromRecommendations(userId)
    showToast('已跳过')
  },

  /**
   * 认证用户点赞
   */
  handleVerifiedUserLike(e) {
    const userId = e.currentTarget.dataset.userId
    console.log('❤️ 认证用户点赞:', userId)
    
    // 调用点赞API
    post('/api/user/like', { targetUserId: userId })
      .then(data => {
        if (data.isMatch) {
          // 匹配成功
          this.showMatchSuccess(data.matchedUser)
        } else {
          showSuccess('已表达喜欢')
        }
      })
      .catch(error => {
        console.error('点赞失败:', error)
        showError('操作失败，请重试')
      })
  },

  /**
   * 从推荐列表中移除用户
   */
  removeUserFromRecommendations(userId) {
    const recommendations = this.data.recommendations.filter(user => user.userId !== userId)
    this.setData({ recommendations })
    
    // 如果推荐列表变少，加载更多
    if (recommendations.length < 3) {
      this.loadMoreRecommendations()
    }
  },

  /**
   * 显示匹配成功
   */
  showMatchSuccess(matchedUser) {
    console.log('💕 显示匹配成功:', matchedUser)
    
    this.setData({
      matchedUser,
      showMatchSuccess: true
    })
  },

  /**
   * 隐藏匹配成功
   */
  hideMatchSuccess() {
    this.setData({
      showMatchSuccess: false,
      matchedUser: null
    })
  },

  /**
   * 开始聊天
   */
  startChat() {
    if (!this.data.matchedUser) return
    
    const userId = this.data.matchedUser.userId || this.data.matchedUser.userNum
    console.log('💬 开始聊天:', userId)
    
    this.hideMatchSuccess()
    
    // 跳转到聊天页面
    navigateTo(`/pages/chat/chat?userId=${userId}`)
  },

  /**
   * 触摸开始
   */
  onTouchStart(e) {
    this.setData({
      touchStartX: e.touches[0].clientX,
      touchStartY: e.touches[0].clientY,
      isDragging: false
    })
  },

  /**
   * 触摸移动
   */
  onTouchMove(e) {
    const deltaX = e.touches[0].clientX - this.data.touchStartX
    const deltaY = e.touches[0].clientY - this.data.touchStartY
    
    // 判断是否为水平滑动
    if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 10) {
      this.setData({
        isDragging: true,
        swipeDirection: deltaX > 0 ? 'right' : 'left'
      })
    }
  },

  /**
   * 触摸结束
   */
  onTouchEnd(e) {
    if (!this.data.isDragging) return
    
    const deltaX = e.changedTouches[0].clientX - this.data.touchStartX
    const threshold = 100 // 滑动阈值
    
    if (Math.abs(deltaX) > threshold) {
      const index = e.currentTarget.dataset.index
      const userId = e.currentTarget.dataset.userId
      
      if (deltaX > 0) {
        // 右滑 - 喜欢
        this.handleLike({ currentTarget: { dataset: { userId } } })
      } else {
        // 左滑 - 跳过
        this.handleSkip({ currentTarget: { dataset: { userId } } })
      }
    }
    
    this.setData({
      isDragging: false,
      swipeDirection: ''
    })
  }
})